/*
 * @Author: Wangjun
 * @Date: 2023-09-01 13:39:49
 * @LastEditTime: 2023-11-18 21:19:53
 * @LastEditors: wangjun haodreams@163.com
 * @Description:创建默认的router
 * @FilePath: \xrdatad:\go\src\gitee.com\haodreams\golib\autoroute\defaulter\default.go
 * hnxr
 */
package defaulter

import (
	"gitee.com/haodreams/golib/autoroute"
	"gitee.com/haodreams/golib/autoroute/minauth"
	"gitee.com/haodreams/golib/startruntime"
	"gitee.com/haodreams/libs/config"
	"gitee.com/haodreams/libs/easy"
	"github.com/gin-contrib/gzip"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
)

// 创建默认的路由
func DefaultEngine(defaultUser func() (string, string), ginModes ...string) (router *gin.Engine) {
	if len(ginModes) > 0 {
		gin.SetMode(ginModes[0])
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	router = gin.New()
	//安全扫描出现的响应头缺失安全问题
	router.Use(SecureHeader)
	//需要认证相关的功能
	UseDefaultAuth(
		defaultUser, // 需要认证的方法
		func(c *gin.Context) (ptr interface{}, err error) {
			//如果是本地发起的请求则不需要认证
			host := c.RemoteIP()
			if host == "127.0.0.1" { //本地不做验证
				return nil, nil
			}
			return minauth.CallbackNeedAuth(c)
		},
	)
	minauth.Save()

	router.Static("/static", "static")
	router.StaticFile("/favicon.ico", "static/favicon.ico")

	if config.DefaultBool("pprof.enable", false) {
		pprof.Register(router)
	}
	router.Use(gin.Recovery())
	//开启压缩
	router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPathsRegexs([]string{".*"})))
	router.StaticFile("/", "static/dist/index.html")
	router.GET("/StartTime", func(c *gin.Context) { //获取运行时间
		c.String(200, easy.FormatTime(startruntime.GetStartRunTime()))
	})

	//多个模板文件
	//router.LoadHTMLGlob("views/**/*")
	autoroute.Normal(router, "/v1/log/*path", &LogController{})
	autoroute.Normal(router, "/v1/login/*path", &LoginController{})

	return router
}
